#include "../logs/bitlog.h"
#include <unistd.h>

enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};
class RollByTimeSink : public bitlog::LogSink
{
public:
    RollByTimeSink(const std::string &basename, TimeGap gap_type) : _basename(basename)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        _cur_gap = _gap_size == 1 ? bitlog::util::Date::now() : bitlog::util::Date::now() % _gap_size; // 获取当前是第几个时间段
        std::string filename = createNewFile();
        bitlog::util::File::createDirectory(bitlog::util::File::path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    void log(const char *data, size_t len)
    {
        time_t cur = bitlog::util::Date::now();
        if ((cur % _gap_size) != _cur_gap)
        {
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
            _cur_gap = _gap_size == 1 ? bitlog::util::Date::now() : bitlog::util::Date::now() % _gap_size;
        }
        _ofs.write(data, len);
        assert(_ofs.good()); // 判断当前的这个操作句柄是否还是正常的
    }

private:
    std::string createNewFile()
    {
        time_t t = bitlog::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";
        return filename.str();
    }

private:
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;  // 当前是第几个时间段
    size_t _gap_size; // 时间段大小
};


int main()
{
    // //读取文件数据，一点一点写入缓冲区，最终将缓冲区数据写入文件，判断生成的新文件与源文件是否一致
    // std::ifstream ifs("./logfile/test.log",std::ios::binary);
    // if(ifs.is_open()==false){std::cout<<"open failed!\n";return -1;}
    // ifs.seekg(0,std::ios::end);//读写位置跳转到末尾
    // size_t fsize=ifs.tellg();//获取当前读写位置相对于起始位置的偏移量
    // ifs.seekg(0,std::ios::beg);
    // std::string body;
    // body.resize(fsize);
    // ifs.read(&body[0],fsize);//不能用&body.c_str(),因为这是一个const char*,没办法修改指向空间的内容，所以用&body[0]@@@@@@@@@@@@@@@@@@@@@@@@@@@@
    // if(ifs.good()==false){std::cout<<"read error\n";return -1;}
    // ifs.close();

    // std::cout<<fsize<<std::e,ndl;
    // bitlog::Buffer buffer;
    // for(int i=0;i<body.size();i++)
    // {
    //     buffer.push(&body[i],1);
    // }

    // std::cout<<buffer.readAbleSize()<<std::endl;
    // std::ofstream ofs("./logfile/tmp.log",std::ios::binary);

    // //ofs.write(buffer.begin(),buffer.readAbleSize());
    // size_t rsize=buffer.readAbleSize();
    // for(int i=0;i<rsize;i++){
    //     ofs.write(buffer.begin(),1);
    //     if(ofs.good()==false){std::cout<<"write error!\n";return -1;}
    //     buffer.moveReader(1);
    // }
    // if(ofs.good()==false){std::cout<<"write error!\n";return -1;}
    // ofs.close();

    // std::string logger_name="sync_logger";
    // bitlog::LogLevel::value limit=bitlog::LogLevel::value::WARN;
    // bitlog::Formatter::ptr fmt(new bitlog::Formatter("[%d{%H:%M:%S}][%c][%f:%l][%p]%T%m%n"));
    // bitlog::LogSink::ptr stdout_lsp = bitlog::SinkFactory::create<bitlog::StdoutSink>();
    // bitlog::LogSink::ptr file_lsp = bitlog::SinkFactory::create<bitlog::FileSink>("./logfile/test.log");
    // bitlog::LogSink::ptr roll_lsp = bitlog::SinkFactory::create<bitlog::RollBySizeSink>("./logfile/roll-", 1024 * 1024);
    // std::vector<bitlog::LogSink::ptr>sinks={stdout_lsp,file_lsp,roll_lsp};
    // bitlog::Logger::ptr logger(new bitlog::SyncLogger(logger_name,limit,fmt,sinks));

    std::unique_ptr<bitlog::LoggerBuilder> builder(new bitlog::GlobalLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerLevel(bitlog::LogLevel::value::WARN);
    builder->buildFormatter("[%c][%f:%l]%m%n");
    builder->buildLoggerType(bitlog::LoggerType::LOGGER_ASYNC);
    builder->buildEnableUnSafeAsync();
    builder->buildSink<RollByTimeSink>("./logfile/roll-async-by=size",TimeGap::GAP_SECOND);
    bitlog::Logger::ptr logger =builder->build();

    size_t cur=bitlog::util::Date::now();
    while(bitlog::util::Date::now()<cur+5)
    {
        logger->fatal("这是一条测试日志");
        usleep(1000);
    }

    // bitlog::LogMsg msg(bitlog::LogLevel::value::INFO, 53, "main.c", "root", "格式化功能测试...");
    // bitlog::Formatter fmt;
    // std::string str = fmt.format(msg);
    // // bitlog::LogSink::ptr stdout_lsp = bitlog::SinkFactory::create<bitlog::StdoutSink>();
    // // bitlog::LogSink::ptr file_lsp = bitlog::SinkFactory::create<bitlog::FileSink>("./logfile/test.log");
    // // bitlog::LogSink::ptr roll_lsp = bitlog::SinkFactory::create<bitlog::RollBySizeSink>("./logfile/roll-", 1024 * 1024);
    // bitlog::LogSink::ptr time_lsp = bitlog::SinkFactory::create<RollByTimeSink>("./logfile/roll-",TimeGap::GAP_SECOND);
    // time_t old=bitlog::util::Date::now();
    // while(bitlog::util::Date::now()<old+5){
    //     time_lsp->log(str.c_str(),str.size());
    //    usleep(1000);
    // }
    // stdout_lsp->log(str.c_str(), str.size());
    // file_lsp->log(str.c_str(), str.size());
    // size_t cursize = 0;
    // size_t count = 0;
    // while (cursize < 1024 * 1024 * 10)
    // {
    //     std::string tmp = str + std::to_string(count++);
    //     roll_lsp->log(tmp.c_str(), tmp.size());
    //     cursize += str.size();
    // }
    // std::cout << bitlog::LogLevel::toString(bitlog::LogLevel::value::DEBUG) << std::endl;
    // std::cout << bitlog::LogLevel::toString(bitlog::LogLevel::value::INFO) << std::endl;
    // std::cout << bitlog::LogLevel::toString(bitlog::LogLevel::value::WARN) << std::endl;
    // std::cout << bitlog::LogLevel::toString(bitlog::LogLevel::value::ERROR) << std::endl;
    // std::cout << bitlog::LogLevel::toString(bitlog::LogLevel::value::FATAL) << std::endl;
    // std::cout << bitlog::LogLevel::toString(bitlog::LogLevel::value::OFF) << std::endl;

    // std::cout<<bitlog::util::Date::now()<<std::endl;
    // std::string pathname="./abc/bcd/a.txt";
    // bitlog::util::File::createDirectory(bitlog::util::File::path(pathname));
    return 0;
}